// import { good } from '../models/index'
const { good, shop, translation, kind } = require('../models/index')
const _ = require('lodash')
const errorHelper = require('../util/errorHelper')

class GoodController {
  // constructor() {}

  async createGoods(goods) {
    const result = await good.bulkCreate(goods)
    if (!result.length) {
      throw errorHelper(400, 'post data error')
    }
    return result
  }

  async upsertGood(goodData) {
    // { returning: true } only for postgress
    const result = await good.upsert(goodData)
    return result
  }

  async delete(goods) {
    // for (let i = 0; i < goods.length; i++) {
    //   // eslint-disable-next-line
    //   await good.destroy({ where: goods[i] })
    // }
    const promiseArr = []
    _.forEach(goods, async (item) => {
      // await good.update({ disable: true }, { where: item })
      promiseArr.push(
        await good.update(
          {
            disable: true
          },
          {
            where: item
          }
        )
      )
    })
    return Promise.all(promiseArr).then((data) => {
      return true
    })
  }

  static async findByKind(kindId) {
    await good.findAll({
      where: {
        kindId
      }
    })
  }

  async getGoods({ shopId, page, countPerPage }) {
    if (page && countPerPage) {
      const goods = await good.findAll({
        limit: countPerPage,
        offset: countPerPage * (page - 1),
        include: [
          {
            model: translation,
            as: 'translation'
          }
        ]
      })
      if (!goods.length) {
        throw errorHelper(400, 'field error')
      }
      return goods
    }
    // 如果没有page countPerPage 返回某个商家的全部商品（之前写在shop中的搬过来//TODO:）
    const targetShop = await kind.findAll({
      where: {
        disable: false,
        shopId
      },
      attributes: ['id', 'name'],
      include: [
        {
          model: good,
          as: 'goods',
          where: {
            disable: false
          },
          required: false,
          include: [
            {
              model: translation,
              as: 'translation'
            }
          ]
        }
      ]
    })
    if (!targetShop.length) {
      throw errorHelper(400, 'no kinds and goods')
    }
    return targetShop
  }
  async count() {
    const count = await good.count()
    return count
  }
}
module.exports = new GoodController()
